<?php
/**
 * Wrapper
 *
 * This is a filter plugin. It will wrap the content with a template - sandwich
 * it. The wrapper template can be set via the Wrapper::template method. If it's
 * not set, then Spaph::getInstance()->config()->plugin->wrapper->template will
 * be checked.
 *
 * The wrapper template should have <?php echo $this->content?> somewhere in it.
 * Other variables can be snuck in by adding them to the config file.
 *
 * = Config file =
 *
 *    plugin.wrapper.view.title = blah
 *    plugin.wrapper.view.divContainerId = #alert
 *
 * = Grab a wrapper object =
 *
 *    $wrapper = Spaph->getInstance()->getPlugin('wrapper');
 *
 * = Add some variables to the wrapper's view object
 *
 *     $wrapper->view->somevar = 'val'
 *     $wrapper->view->head    = array();
 *     $wrapper->view->head[]  = '<script type="text/javascript"...';
 *
 * = Attach wrapper to view =
 *
 *   $this->view = Spaph::getInstance()->view('Wrapper');
 *
 */
class Wrapper extends Spaph_Plugin
{
    private $template = '';
    public  $view     = '';

    public function __construct()
    {
        $this->view = Spaph::getInstance()->view();
        
        // Look for plugin.wrapper.view.somevar = blah
        if(Spaph::getInstance()->config()->plugin->wrapper->view) {
            foreach(Spaph::getInstance()->config()->plugin->wrapper->view->toArray() as $key => $val) {
                $this->view->$key = $val;
            }
        }
    }

    public function _filter($content)
    {
        $template = $this->template();
        
        $this->view->bodyID  = implode('-',array_reverse(Spaph::getInstance()->getAction()));
        $this->view->content = "<!-- Wrapper -->\n".$content."\n<!-- /Wrapper -->\n";
        
        $content = $this->view->render($template);

        return $content;
    }

    /**
     * template
     *
     * Get the name of the wrapper template.
     *
     * Spaph::getInstance()->getPlugin('Wrapper')->template('mywrapper.tpl.php');
     *
     * @param string $name
     */
    public function template($name=null)
    {
        if(isset($name)) {
            $this->template = $name;
            return $name;
        }

        if($this->template) {
            return $this->template;
        }
        else if(Spaph::getInstance()->config()->plugin->wrapper->template) {
            return Spaph::getInstance()->config()->plugin->wrapper->template;
        }

        throw new Exception('The template wrapper is not defined.');
    }
}

